package com.woniu.view;

import com.woniu.controller.*;
import com.woniu.entity.*;
import com.woniu.mapper.GoodsMapper;
import com.woniu.mapper.OrderItemsMapper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

public class ToUserPage {

    public static void userPage(Users users) {
        boolean flag = true;
        while (flag){
            System.out.println("_________________________");
            System.out.println("|------欢迎进入用户系统-----|");
            System.out.println("|--------1.购买商品--------|");
            System.out.println("|--------2.查看购物车------|");
            System.out.println("|--------3.订单管理--------|");
            System.out.println("|--------4.账户充值--------|");
            System.out.println("|--------5.退货-----------|");
            System.out.println("|--------6.查看个人信息-----------|");
            System.out.println("|--------7.退出-----------|");
            System.out.println("--------------------------");
            Scanner sc = new Scanner(System.in);
            System.out.println("请选择你的操作：");
            int choice=sc.nextInt();
            switch (choice){
                case 1:
                    System.out.println("购买商品");
                    List<Product> products = shouwProduct();
                    addorderitems(users,products);
                    break;
                case 2:
                    System.out.println("查看购物车");
                    placeOrder(users);
                    break;
                case 3:
                    System.out.println("订单管理");
                    manageOrders(users);
                    break;
                case 4:
                    System.out.println("账户充值");
                    addUserMoney(users);
                    break;
                case 5:
                    System.out.println("退货");
                    deleteOrders(users);
                    break;
                case 6:
                    viewprofile(users);
                    break;
                case 7:
                    flag = false;//结束循环(退出系统)
                    break;
                default:
                    System.out.println("你输入有误！请重选选择");
                    break;
            }
        }
    }
    /**
     * 查看个人信息
     * */
    public static void viewprofile(Users users) {
         Power power = PowerController.selectPowerById(users.getPower_id());
        System.out.println("id\t姓名\t密码\t电话\t余额\t身份");
        System.out.println(users.getUser_id()+"\t"+users.getUsername()+"\t"+users.getPwd()+"\t"+users.getTelphone()+"\t"+users.getMoney()+"\t"+power.getPname());
        System.out.println("是否更改个人信息");
        System.out.println("输入y更改");
        System.out.println("输入n不更改");
        Scanner sc = new Scanner(System.in);
        String ch=sc.nextLine();
        if(ch.equals("y")){
            System.out.println("选择要修改的信息");
            System.out.println("1.修改用户名");
            System.out.println("2.修改密码");
            System.out.println("3.修改手机号");
            int choice=sc.nextInt();
            switch (choice){
                case 1:
                    System.out.println("输入修改后的名字");
                    String name = sc.next();
                    UserController.updateUserName(name, users.getUser_id());
                    System.out.println("修改成功");
                    break;
                    case 2:
                        System.out.println("输入要修改的密码");
                        String password = sc.next();
                        UserController.updateUserPwd(password,users.getUser_id());
                        System.out.println("修改成功");
                        break;
                        case 3:
                            System.out.println("修改要修改的手机号");
                            String phone = sc.next();
                            UserController.updateUserTelphone(phone,users.getUser_id());
                            System.out.println("修改成功");
                            break;
                            default:
                                System.out.println("无此操作");
                                break;
            }
        }else if(ch.equals("n")){
            System.out.println("退出");
        }
    }

    /**
     * 退货
     * */
    public static void deleteOrders(Users users) {
        List<Orders> allOrders = OrdersController.getAllOrders(users.getUser_id());
        for (Orders order : allOrders) {
            if (order.getStatus()==1 || order.getStatus()==5){
                System.out.println(order);
            }
        }
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要退货的订单号");
        Integer OrderId = sc.nextInt();
        OrdersController.updateOrdersStatus(OrderId,4);
        List<OrderItems> orderItems = OrderItemsCotroller.getOrderItems(OrderId);
        for (OrderItems orderItem : orderItems) {
            OrderItemsCotroller.updateOrderItemsByOrderId(orderItem.getOrder_id(),4);
        }
    }

    /**
     * 订单管理
     * */
    public static void manageOrders(Users users) {
        System.out.println("请选择操作");
        System.out.println("1.查看订单详情");
        System.out.println("2.支付未支付的订单");
        System.out.println("3.删除未支付的订单");
        System.out.println("4.确认订单");
        Scanner sc = new Scanner(System.in);
        int choice=sc.nextInt();
        switch (choice){
            case 1:
                System.out.println("查看订单详情");
                checkOrders(users);
                break;
                case 2:
                    System.out.println("支付未支付的订单");
                    payOrders(users);
                    break;
                    case 3:
                        System.out.println("删除未支付的订单");
                        deleteOrdersPay(users);
                        break;
                        case 4:
                            System.out.println("确认订单");
                            notarizeOrders(users);
                            break;
                        default:
                            System.out.println("无此操作");
                            break;
        }
    }
    /**
     * 确认订单
     * */
    public static void notarizeOrders(Users users) {
      List<Orders> orders = OrdersController.selectOrdersUidStatus(users.getUser_id(), 3);
      for (Orders order : orders) {
          System.out.println(order);
      }
        System.out.println("请选择你要确认的订单号");
      Scanner sc = new Scanner(System.in);
      int orderId=sc.nextInt();
      OrdersController.updateOrdersStatus(orderId,5);
      OrderItemsCotroller.updateOrderItemsByOrderId(orderId,5);
        System.out.println("已完成");
    }
    /**
     * 删除未支付的订单
     * */
    public static void deleteOrdersPay(Users users){
        List<Orders> orders = OrdersController.selectOrdersUidStatus(users.getUser_id(), 2);
        for (Orders order : orders) {
            System.out.println(order);
        }
        System.out.println("请选择你要删除的未支付订单");
        Scanner sc = new Scanner(System.in);
        int orderId=sc.nextInt();
        OrdersController.deleteOrdersByorderId(orderId);
        OrderItemsCotroller.deleteOrderItems(orderId);
    }
    /**
     * 支付未支付的订单
     * */
    public static void payOrders(Users users) {
        List<Orders> orders = OrdersController.selectOrdersUidStatus(users.getUser_id(), 2);
        for (Orders order : orders) {
            System.out.println(order);
        }
        System.out.println("请选择你要支付的未支付订单");
        Scanner sc = new Scanner(System.in);
        int orderId=sc.nextInt();
        Orders orders1 = OrdersController.selectOrdersByOrderID(orderId);
        if (users.getMoney()>=orders1.getTotal()){
                    UserController.updateUserMoney(users.getUser_id(), orders1.getTotal());
                    OrdersController.updateOrdersStatus(orderId,1);
                    List<OrderItems> orderItems = OrderItemsCotroller.getOrderItems(orderId);
                    for (OrderItems orderItem : orderItems) {
                        OrderItemsCotroller.updateOrderItemsByOrderId(orderItem.getOrder_id(),1);
                        ProductController.updateProductStock(orderItem.getProduct_id(),orderItem.getQuantity());
                        UserController.updateUserMoney(orderItem.getMerchant_id(),-orderItem.getPrice());
                    }
        }else {
            System.out.println("余额不足,请充值");
        }
    }
    /**
     * 查看当前用户的订单和订单详情
     * */
    public static void checkOrders(Users users){
        System.out.println("1.查看所有订单");
        System.out.println("2.通过商品和商家查");
        Scanner sc = new Scanner(System.in);
        int choice=sc.nextInt();
        if(choice==1){
            List<Orders> allOrders = OrdersController.getAllOrders(users.getUser_id());
            for (Orders order : allOrders){
                System.out.println("订单编号\t订单价格\t订单状态\t订单时间");
                Date updatedAt = order.getUpdated_at();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = formatter.format(updatedAt);
                State state = StateController.selectStateById(order.getStatus());
                System.out.println(order.getOrder_id()+"\t"+order.getTotal()+"\t"+state.getStatus()+"\t"+format);
                List<OrderItems> orderItems = OrderItemsCotroller.getOrderItems(order.getOrder_id());
                System.out.println("订单详情:");
                System.out.println("订单详情编号\t商品\t数量\t价格\t商品详情\t订单状态\t商家");
                for (OrderItems orderItem : orderItems){
                    Product productById = ProductController.getProductById(orderItem.getProduct_id());
                    State state1 = StateController.selectStateById(orderItem.getStatus());
                    Integer merchantId = productById.getMerchant_id();
                    Users users1 = UserController.selectUserByUid(merchantId);
                    System.out.println(orderItem.getOrder_item_id()+"\t"+productById.getPname()+"\t"+orderItem.getQuantity()+"\t"+orderItem.getPrice()+"\t"+productById.getDes()+"\t"+state1.getStatus()+"\t"+ users1.getUsername());
                }
            }
        }else if(choice==2){
            System.out.println("1.请输入商家的名字");
            String mname = sc.next();
            Users merchant = UserController.selectUserByName(mname);
            System.out.println("2.请输入商品的名字");
            String pname = sc.next();
            List<Product> products = ProductController.selectProductByName(pname);
            System.out.println("订单编号\t商品\t数量\t价格\t商品详情\t订单状态\t商家");
            if (mname.equals("null")){
                for (Product product : products){
                    List<OrderItems> orderItems = OrderItemsCotroller.selectOrderItemsByPid(product.getPid());
                    for (OrderItems orderItem : orderItems){
                        Orders orders = OrdersController.selectOrdersByOrderID(orderItem.getOrder_id());
                        if(orders.getUser_id()== users.getUser_id()){
                            State state = StateController.selectStateById(orderItem.getStatus());
                            System.out.println(orderItem.getOrder_item_id()+"\t"+product.getPname()+"\t"+orderItem.getQuantity()+"\t"+orderItem.getPrice()+"\t"+product.getDes()+"\t"+state.getStatus()+"\t"+orderItem.getMerchant_id());
                        }
                    }
                }
            }else if (pname.equals("null")){
                List<OrderItems> orderItemsByMid = OrderItemsCotroller.getOrderItemsByMid(merchant.getUser_id());
                for (OrderItems orderItem : orderItemsByMid){
                     Orders orders = OrdersController.selectOrdersByOrderID(orderItem.getOrder_id());
                     if (orders.getUser_id()==users.getUser_id()){{
                         Product product = ProductController.getProductById(orderItem.getProduct_id());
                         State state = StateController.selectStateById(orderItem.getStatus());
                         System.out.println(orderItem.getOrder_item_id()+"\t"+product.getPname()+"\t"+orderItem.getQuantity()+"\t"+orderItem.getPrice()+"\t"+product.getDes()+"\t"+state.getStatus()+"\t"+ merchant.getUsername());
                     }}
                }
            }else {
                for (Product product : products) {
                    List<OrderItems> orderItemsByPid = OrderItemsCotroller.getOrderItemsByPid(merchant.getUser_id(), product.getPid());
                    for (OrderItems orderItem : orderItemsByPid) {
                        Orders orders = OrdersController.selectOrdersByOrderID(orderItem.getOrder_id());
                        State state = StateController.selectStateById(orderItem.getStatus());
                        if (orders.getUser_id()==users.getUser_id()){
                            System.out.println(orderItem.getOrder_item_id()+"\t"+product.getPname()+"\t"+orderItem.getQuantity()+"\t"+orderItem.getPrice()+"\t"+product.getDes()+"\t"+state.getStatus()+"\t"+ merchant.getUsername());
                        }
                    }
                }
            }
        }
    }
    /**
     * 用户充值
     * */
    public static void addUserMoney(Users users) {
        Scanner sc = new Scanner(System.in);
        double addMoney=sc.nextDouble();
        UserController.updateUserMoney(users.getUser_id(),-addMoney);
    }

    /**
     * 展示购物车
     * */
    public static List<Goods> shouwGoods(Users users) {
        List<Goods> goods = GoodsController.selectAllGoods(users.getUser_id());
        goods.forEach(System.out::println);
        return goods;
    }
    /**
     * 购物车中下订单
     * */
    public static void placeOrder(Users users) {
        List<Goods> goods = shouwGoods(users);
        Scanner sc = new Scanner(System.in);
        System.out.println("请选择操作");
        System.out.println("1.清空购物车");
        System.out.println("2.修改购物车的商品数量");
        System.out.println("3.删除购物车指定的商品");
        System.out.println("4.退出");
        int choice = sc.nextInt();
        if (choice == 1){
            Double totalPrice = 0.0;
            for (Goods good : goods) {
                totalPrice += good.getPrice()*good.getStock();
            }
            if(users.getMoney()>=totalPrice){
                Orders orders = new Orders(null, users.getUser_id(), totalPrice,1,new Date(),new Date());
                OrdersController.insertOrder(orders);
            }else {
                Orders orders = new Orders(null, users.getUser_id(), totalPrice,2,new Date(),new Date());
                OrdersController.insertOrder(orders);
                System.out.println("余额不足");
            }
            /**
             * 添加订单详情
             * */
            List<Orders> allOrders = OrdersController.getAllOrders(users.getUser_id());
            Integer status = allOrders.get(allOrders.size() - 1).getStatus();
            Integer orderId = allOrders.get(allOrders.size() - 1).getOrder_id();
            for(Goods good : goods){
                Integer pid =good.getPid();
                Integer stock = good.getStock();
                double price = good.getPrice() * stock;
                OrderItems orderItems = new OrderItems(null,orderId,pid,stock,price,new Date(),good.getMerchant_id(),status);
                OrderItemsCotroller.insertOrderItems(orderItems);
                Integer merchantId =good.getMerchant_id();
                if(status == 1){
                    ProductController.updateProductStock(pid,stock);
                    UserController.updateUserMoney(merchantId,-price);
                }
            }
            if (status == 1){
                UserController.updateUserMoney(users.getUser_id(),allOrders.get(allOrders.size() - 1).getTotal());
            }
            GoodsController.deleteGoodsByUid(users.getUser_id());
            /**
             * 打印订单
             * */
            System.out.println("订单号:"+allOrders.get(allOrders.size() - 1).getOrder_id());
            System.out.println("--------------购买商品详情如下-------------");
            System.out.println("商品编号\t商品名称\t商品数量\t单价\t商品总价");

            List<OrderItems> orderItems = OrderItemsCotroller.getOrderItems(orderId);
            for(OrderItems orderItem : orderItems){
                Product productById = ProductController.getProductById(orderItem.getProduct_id());
                System.out.println(productById.getPid()+"\t"+productById.getPname()+"\t"+orderItem.getQuantity()+"\t"+productById.getPrice()+"\t"+orderItem.getPrice());
            }
            System.out.println("-----------------------------");
            System.out.println("\t\t\t\t\t\t订单总价："+allOrders.get(allOrders.size() - 1).getTotal());
            Date updatedAt = allOrders.get(allOrders.size() - 1).getUpdated_at();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = formatter.format(updatedAt);
            System.out.println("\t\t\t\t\t\t日期："+format);
            /**
             * 修改购物车商品数量
             * */
        }else if (choice == 2){
            System.out.println("修改购物车的商品数量");
            List<Goods> goods1 = GoodsController.selectAllGoods(users.getUser_id());
            for (Goods good : goods1) {
                System.out.println(good);
            }
            System.out.println("输入修改商品的id");
            Integer id = sc.nextInt();
            System.out.println("1.添加商品数量");
            System.out.println("2.减少商品数量");
            int b = sc.nextInt();
           switch (b){
               case 1:
                   System.out.println("输入添加数量");
                   Integer stock1 = sc.nextInt();
                   GoodsController.updateGoods(stock1,id, users.getUser_id());
                   break;
               case 2:
                   System.out.println("减少添加数量");
                   Integer stock2 = sc.nextInt();
                   GoodsController.updateGoods(-stock2,id, users.getUser_id());
                   break;
               default:
                   System.out.println("没这个选项");
                   break;
           }
            System.out.println("修改成功");
           /**
            * 删除购物车指定商品
            * */
        }else if (choice == 3){
            System.out.println("删除购物车指定的商品");
            List<Goods> goods1 = GoodsController.selectAllGoods(users.getUser_id());
            for (Goods good : goods1) {
                System.out.println(good);
            }
            System.out.println("输入要删除的商品id");
            Integer id = sc.nextInt();
            GoodsController.deleteGoodsByUidPid(users.getUser_id(),id);

        }else if (choice == 4){
            System.out.println("已退出");
        }

    }
    /**
     * 展示商品
     * */
    public static List<Product> shouwProduct() {
        System.out.println("搜索商品");
        System.out.println("1.展示所以有商品");
        System.out.println("2.搜索商品");
        Scanner sc = new Scanner(System.in);
        int choice = sc.nextInt();
        if(choice == 1){
            ProductController.getProductList().forEach(System.out::println);
            return ProductController.getProductList();
        }else if(choice == 2){
            System.out.println("输入要搜索的商品");
            String name = sc.next();
            List<Product> products = ProductController.selectProductByName(name);
            products.forEach(System.out::println);
            return products;
        }else {
            System.out.println("没有商品");
        }
        return null;
    }
    /**
     * 购买商品添加购物车或直接下单
     * */
    public static void addorderitems(Users users,List<Product> productList) {
        System.out.println("请选择你要购买的商品");
        Scanner sc = new Scanner(System.in);
        int pid=sc.nextInt();
        System.out.println(ProductController.getProductById(pid));
        Product productById = ProductController.getProductById(pid);
        if (productById != null){
            System.out.println("购买数量");
            int quantity=sc.nextInt();
            if(quantity>0 && (quantity <= productById.getStock())){
                System.out.println("请选择方式");
                System.out.println("1,添加购物车");
                System.out.println("2，直接下单");
                int a=sc.nextInt();
                /**
                 * 添加购物车
                 * */
                if(a==1){
                   Goods goods1 = GoodsController.selectGoods(productById.getPid(), users.getUser_id());
                    if(goods1==null){
                        Goods goods = new Goods(null,pid,productById.getPname(),productById.getPrice(),quantity, users.getUser_id(),productById.getMerchant_id());
                        GoodsController.insertGoods(goods);
                    }else {
                        GoodsController.updateGoods(quantity,productById.getPid(),users.getUser_id());
                    }
                    /**
                     * 直接下单
                     * */
                }else if(a==2){
                    Double total = productById.getPrice() * quantity;
                    if(total>users.getMoney()){
                        Orders orders = new Orders(null,users.getUser_id(),total,2,new Date(),new Date());
                        OrdersController.insertOrder(orders);
                        System.out.println("余额不足");
                    }else {
                        Orders orders = new Orders(null,users.getUser_id(),total,1,new Date(),new Date());
                        OrdersController.insertOrder(orders);
                    }
                    List<Orders> allOrders = OrdersController.getAllOrders(users.getUser_id());
                    Integer orderId = allOrders.get(allOrders.size() - 1).getOrder_id();
                    Double price = allOrders.get(allOrders.size() - 1).getTotal();
                    Integer status = allOrders.get(allOrders.size() - 1).getStatus();
                    OrderItems orderItems = new OrderItems(null,orderId,productById.getPid(),quantity,price,new Date(),productById.getMerchant_id(),status);
                    OrderItemsCotroller.insertOrderItems(orderItems);
                    Integer merchantId = productById.getMerchant_id();
                    if(status==1){
                        UserController.updateUserMoney(users.getUser_id(),price);
                        UserController.updateUserMoney(merchantId,-price);
                        ProductController.updateProductStock(productById.getPid(),quantity);
                    }
                    //打印订单
                    System.out.println("订单号:"+allOrders.get(allOrders.size() - 1).getOrder_id());
                    System.out.println("--------------购买商品详情如下-------------");
                    System.out.println("商品编号\t商品名称\t商品数量\t单价\t商品总价");
                    System.out.println(productById.getPid()+"\t"+productById.getPname()+"\t"+quantity+"\t"+productById.getPrice()+"\t"+price);
                    System.out.println("-----------------------------------------");
                    System.out.println("\t\t\t\t\t\t订单总价"+allOrders.get(allOrders.size() - 1).getTotal());
                    Date updatedAt = allOrders.get(allOrders.size() - 1).getUpdated_at();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String format = formatter.format(updatedAt);
                    System.out.println("\t\t\t\t\t\t日期："+format);
                }else{
                    System.out.println("没有此操作");
                }
            }else {
                System.out.println("库存不足，请重新输入");
            }
        }else {
            System.out.println("暂无此商品");
        }
    }

}
